package com.bestv.datalake.controller;

import com.alibaba.fastjson.JSONArray;
import com.bestv.datalake.exception.ExceptionResponse;
import com.bestv.datalake.exception.LogRuleConflictException;
import com.bestv.datalake.exception.LogRuleExistException;
import com.bestv.datalake.exception.LogRuleNotFoundException;
import com.bestv.datalake.model.LogRuler;
import com.bestv.datalake.service.LogRulerService;
import com.wwh.login.shjtaq.LoginUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zg on 2016/6/27.
 */
@RestController
@RequestMapping("/datalake/v1/logRules")
@Api(value = "LogRule", description = "提供LogRule相关CURD服务")
public class LogRulerController {

    private Logger logger = Logger.getLogger(LogRulerController.class);

    @Autowired
    private LogRulerService logRulerService;

//    @Autowired
//    private CityRepository cityRepository;


    @RequestMapping(value="",method= RequestMethod.GET)
    @ApiOperation(value="Get LogRules", notes = "列出所有日志解析规则，支持主题过滤", produces="application/json", nickname = "getLogRules")
    public List<LogRuler> getLogRulerBySubject(@RequestParam(value="subjectName",required = false) String subjectName) {
        if(subjectName!=null) {
            LogRuler lp = logRulerService.getLogRulerBySubject(subjectName);
            if(lp==null){
                throw new LogRuleNotFoundException("当前主题对应的日志解析规则没有找到，主题=" + subjectName);
            }
            else {
                List<LogRuler> list = new ArrayList<LogRuler>();
                list.add(lp);
                return list;
            }
        }
        else{
            return logRulerService.getAllLogRulers();
        }
    }

    @RequestMapping(value="/{logRulerId}",method= RequestMethod.GET)
    @ApiOperation(value="Get LogRule", notes = "获得指定的日志解析规则", produces="application/json", nickname = "getLogRule")
    public LogRuler getLogRuler(@PathVariable Long logRulerId){
        this.validateLogRulerByID(logRulerId);
        //return this.logRuleRepository.findById(logRuleId).get();
        return logRulerService.getLogRulerByLogRuleId(logRulerId);
    }

    @RequestMapping(value="/fd/{fadanNo}",method= RequestMethod.GET)
    @ApiOperation(value="Get LogRule1", notes = "获得指定的日志解析规则1", produces="application/json", nickname = "getLogRule1")
    public String getLogRuler1(@PathVariable String fadanNo){
        String username = "zigao93j";
        String password = "zigao93jQQQ";
        String softid = "896594";
        String chromApplicationPath = null;// "C:\\Program Files (x86)\\Google\\Chrome\\Application";
        //�ȸ���������Ŀ¼
        String chromeDriverpath = "D:\\wwhprojects\\gitee\\jingzigao----------\\jiaotong\\tm\\chromedriver\\chromedriver_win32\\chromedriver.exe";
//        chromApplicationPath="D:\\Program Files (x86)\\ChromeX86\\Application\\chrome.exe";


//        chromApplicationPath="/opt/google/chrome/google-chrome";
//        chromeDriverpath ="/root/chromedriver_linux64/chromedriver";
        chromeDriverpath="C:\\soft\\chromedriver_win32\\chromedriver.exe";
        chromApplicationPath="C:\\soft\\ChromeX86\\Application\\chrome.exe";
        String results="";
        //��¼
        LoginUtil loginUtil4Chaoying = LoginUtil.getInstance4Chaoying(username, password, softid, chromApplicationPath, chromeDriverpath);
        //return this.logRuleRepository.findById(logRuleId).get();
        LoginUtil loginUtil = new LoginUtil();
        boolean isLogin = loginUtil.doLoginAction("420124198102210473","1234qwer",true);
        if (isLogin) {
            List<List<String>> lists = loginUtil4Chaoying.queryFadan(fadanNo);
            System.out.println(JSONArray.toJSONString(lists));
            results= JSONArray.toJSONString(lists);
        }
        return results;
    }



    @RequestMapping(value="",method= RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value="Create LogRuler", notes = "新建日志解析规则", produces="application/json", nickname = "createLogRuler")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "创建成功"),
            @ApiResponse(code = 409, message = "该主题对应的日志解析规则已经存在",response = ExceptionResponse.class)
    })
    public LogRuler createLogRuler(@RequestBody LogRuler logRuler){
        if(logRulerService.getLogRulerBySubject(logRuler.getSubjectName())==null) {
             logRulerService.createLogRuler(logRuler);
            return logRulerService.getLogRulerBySubject(logRuler.getSubjectName());
        }
        else{
            throw new LogRuleExistException("该主题对应的日志解析规则已经存在");
        }
    }

    @RequestMapping(value="/{logRuleId}",method= RequestMethod.PUT)
    @ResponseBody
    @ApiOperation(value="Update LogRuler", notes = "更新日志解析规则，注意：日志解析规则ID必须一致", produces="application/json", nickname = "updateLogRuler")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "更新成功"),
            @ApiResponse(code = 404, message = "日志解析规则不存在",response = ExceptionResponse.class),
            @ApiResponse(code = 409, message = "新的日志解析规则内的ID或主题和原来的日志解析规则不一致",response = ExceptionResponse.class)
    })
    public LogRuler updateLogRuler(@PathVariable Long logRuleId, @RequestBody LogRuler logRulerNew){
        validateLogRulerByID(logRuleId);
        LogRuler logRulerOld = logRulerService.getLogRulerByLogRuleId(logRuleId);
        if(logRulerOld.getSubjectName().equals(logRulerNew.getSubjectName())&&logRulerOld.getLogRulerId().equals(logRulerNew.getLogRulerId())) {
            logRulerService.updateLogRuler(logRulerNew);
            return logRulerService.getLogRulerByLogRuleId(logRuleId);
        }else {
            throw new LogRuleConflictException("新的日志解析规则内的ID或主题和原来的日志解析规则不一致");
        }
    }

    @RequestMapping(value="/{logRuleId}",method= RequestMethod.DELETE)
    @ResponseBody
    @ApiOperation(value="Delete LogRuler By ID", notes = "基于日志解析规则ID删除对应解析规则", produces="application/json", nickname = "deleteLogRuleByID")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "更新成功"),
            @ApiResponse(code = 404, message = "日志解析规则不存在",response = ExceptionResponse.class)
    })
    public String deleteLogRuler(@PathVariable Long logRuleId){
        validateLogRulerByID(logRuleId);
        logRulerService.deleteLogRuler(logRuleId);
        return "delete succeed!";
    }

    @RequestMapping(value="",method= RequestMethod.DELETE)
    @ResponseBody
    @ApiOperation(value="Delete LogRuler By SubjectName", notes = "基于主题名称删除对应解析规则", produces="application/json", nickname = "deleteLogRuleBySubjectName")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "更新成功"),
            @ApiResponse(code = 404, message = "日志解析规则不存在",response = ExceptionResponse.class)
    })
    public String deleteLogRuler(@RequestParam(value="subjectName",required = true) String subjectName){
        validateLogRulerBySubjectName(subjectName);
        LogRuler logRuler = logRulerService.getLogRulerBySubject(subjectName);
        logRulerService.deleteLogRuler(logRuler);
        return "sucess";
    }

    private void validateLogRulerByID(Long id) {
        if(logRulerService.getLogRulerByLogRuleId(id)==null){
        throw new LogRuleNotFoundException("当前ID对应的日志解析规则没有找到, ID=" + id);
        }
    }

    private void validateLogRulerBySubjectName(String subjectName) {
        if(logRulerService.getLogRulerBySubject(subjectName)==null) {
            throw new LogRuleNotFoundException("当前主题对应的日志解析规则没有找到，主题=" + subjectName);
        }
    }


}
